<template>
  <section>
    <!--工具条
    v-model="keyword" 接受到的数据
    -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字查询"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="blue" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="blue" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="90" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="90" sortable>
      </el-table-column>
      <el-table-column prop="resources" label="资源" width="150" sortable>
        <template scope="scope">
          <img :src="imgPrefix+scope.row.resources.split(',')[0]" height="50px">
        </template>
      </el-table-column>
      <!--:formatter="formatState"-->
      <el-table-column prop="state" label="状态" width="90" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==1">上架</span>
          <span style="color: red" v-else-if="scope.row.state==-0">下架</span>
          <span style="color: darkblue" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="100" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="100" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination background layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :total="totals"
                     :current-page="currentPage"
                     :page-size="pageSize"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加或修改的对话框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="销售量" prop="salecount">
          <el-input v-model="saveForm.salecount">
          </el-input>
        </el-form-item>
        <el-form-item label="资源" prop="resources">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastdfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.productDetail.intro" :options="quillOption" v-if="saveForm.productDetail">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="orderNotice">
          <quill-editor v-model="saveForm.productDetail.orderNotice"  :options="quillOption" v-if="saveForm.productDetail">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

import {quillEditor} from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,

      departments: [],//显示分页列表数据
      totals: 0,//总数量
      currentPage: 1,//当前页
      pageSize: 5,//每页显示的数量
      listLoading: false,//表格上的加载框

      //多条数据选中
      sels: [],//列表选中列

      //高级查询的数据
      keyword: "",

      //图片显示的前缀：要加上http://
      imgPrefix: "http://123.207.27.208",

      //数据图片
      fileList: [],
      //宠物所在店铺
      shops: [],
      //宠物类型树
      typeTree: [],

      //添加或修改数据
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,//加载框
      title: '',//对话框标题
      saveFormRules: {//验证规则
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入售价', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入进价', trigger: 'blur'}
        ],
      },

      //编辑界面数据
      saveForm: {
        id: null,
        name: '',
        dirPath: '',
        state: 0,
        costprice: 0,
        resources: '',
        salecount:'',
        productDetail: {
          intro: '',
          orderNotice: ''
        }

      },

    }
  },

  methods: {
    //1.分页查询
    getDepartments() {
      let para = {
        //分页参数
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        //高级查询的关键字
        keyword: this.keyword
      };
      //页面一加载就显示加载框
      this.listLoading = true;
      this.$http.post("/product", para).then(res => {
        //给totals赋值总数量 计算分页栏
        this.totals = res.data.totals;
        //赋值分页数据 显示当前页的分页数据
        this.departments = res.data.data;
        //隐藏加载框
        this.listLoading = false;

      }).catch(res => {
        this.$message.error('系统繁忙，请稍后再试！！！！');
      });
    },

    //2.点击某一页触发方法
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },


    //3.关键字查询
    keywordQuery() {
      //关键字从第一行开始查询
      this.currentPage = 1,
          this.getDepartments();
    },


    //4.单行删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {
        //显示加载框
        this.listLoading = true;
        //获取id
        var id = row.id;
        this.$http.delete("/product/" + id).then(res => {
          if (res.data.success) {//删除成功

            let totalPage = this.totals % this.pageSize == 0 ? this.totals / this.pageSize
                : Math.ceil(this.totals / this.pageSize);
            if (this.currentPage > 1 && this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0) {
              this.currentPage = this.currentPage - 1;
            }


            this.$message.success('删除成功');
            this.getDepartments();
          } else {
            this.$message.error('删除失败，请稍后重试500');
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试400，404');
        })
      }).catch(() => {
      });
    },


    //5.选项改变的时候触发
    selsChange: function (sels) {
      this.sels = sels;
    },


    //6.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        /* let para = { ids: ids };*/
        this.$http.patch("/product", ids).then(res => {
          if (res.data.success) {//删除成功
            this.$message.success('批量删除成功');
            this.getDepartments();
          } else {
            this.$message.error('系统繁忙，请稍后重试500');
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试400，404');
        }).catch(() => {
        })
      })

    },


    //7.点击修改弹出对话框
    handleEdit: function (index, row) {
      this.title = "修 改";
      this.saveForm = Object.assign({}, row);

      //图片回显
      this.fileList = [];
      if (this.saveForm.resources) {
        let arr = this.saveForm.resources.split(",")
        for (let i = 0; i < arr.length; i++) {
          this.fileList.push({"url": "http://123.207.27.208" + arr[i]})
        }
      }

      this.saveFormVisible = true;

    },


    //8.点击添加弹出对话框
    handleAdd: function () {
      this.title = "添 加";
      this.getManagers()

      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        dirPath: '',
        state: 0,
        costprice: 0,
        resources: '',
        salecount:'',
        productDetail: {
          intro: '',
          orderNotice: ''
        }
      };
      //清空列表
      this.fileList = [];
      //显示模态框
      this.saveFormVisible = true;
    },

    //9.提交修改或者添加的数据
    editSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            /**
             * type后端对象前端数组
             */
                //点击提交对类型的处理
            let typeArr = this.saveForm.type; //[2,3,5]
            if(typeArr){
              //前端传递type为数组，后端type接收的是PetType类型，如果不处理就会出现400
              para.type = null;
              //将修改之后的宠物类型id赋值给typeId
              para.typeId = typeArr[typeArr.length-1];
            }

            this.$http.put("/product", para).then(res => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if (res.data.success) {
                this.$message.success("操作成功");
                this.getDepartments();
              } else {
                this.$message.error("操作失败【500】")
              }
            }).catch(res => {
              this.$message.error("操作失败【400】,【404】")
            })

          })
        }
      });
    },

    //10.查找所有部门员工的数量
    getManagers() {
      this.$http.get("/petType").then(res => {
        this.managers = res.data;
      })
    },

    //上传一张图片的时候会触发
    handleSuccess(response, file, fileList) {

      if (this.saveForm.resources) {//有值的时候
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      } else {
        this.saveForm.resources = response.resultObj;
      }
      //处理页面回显
      this.fileList = [];//清空
      var resourcesArr = this.saveForm.resources.split(",");
      if (this.saveForm.resources) {
        for (var i = 0; i < resourcesArr.length; i++) {
          this.fileList.push({url: "http://123.207.27.208" + resourcesArr[i]})
        }
      }
    },

    //点击删除某一张图片的处理
    handleRemove: function (file, fileList) {
      //{url: "http://123.207.27.208/group1/M00/00/02/CgAIC2KevEeAX2T4AAEUusLjqqk161.png"}
      //console.log(file);
      //1.调用删除接口删除 fastdfs上的图片
      let url = file.url
      let path = url.substring(url.indexOf("/group1"));
      this.$http.delete("/fastdfs?path=" + path).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败");
        }
      })

      //2.对resource做处理 ：加入path="/group1/MxVcQ8663.jpg"
      // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg,/group1/MxVcQ8663.jpg
      if (this.saveForm.resources) {//只有值
        //["/group1/M00cQ8663.jpg","/group1/MxVcQ8663.jpg","/group1/MxVcQ8663.jpg"]
        let arr = this.saveForm.resources.split(",");
        for (var i = 0; i < arr.length; i++) {
          if (arr[i] == path) {
            //从i开始删除，向后删除1个
            arr.splice(i, 1);
            break;
          }
        }
        this.saveForm.resources = arr.join(","); // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg
      }

      //3.对fileList做处理
      this.fileList = [];
      if (this.saveForm.resources) {//有值
        let arr = this.saveForm.resources.split(",");
        for (var i = 0; i < arr.length; i++) {
          this.fileList.push({"url": "http://123.207.27.208" + arr[i]});
        }
      }
    },



    onsale() {
      //通过itme来获得id
      var ids = this.sels.map(item => item.id)
      //判断是否为空
      if (!this.sels || this.sels.map.length < 1) {
        //提示语
        this.message({managers: "选的数据不能为空，空的你传个得得", type: "error"})
        return;//如果为空直接结束
      }

      this.$confirm('确定要上架？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/product/onsale', ids).then((res) => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message({
              message: '上架成功',
              type: 'success'
            });
            this.getDepartments()
          } else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }

        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
      });
    },

    offsale() {
      //通过itme来获得id
      var ids = this.sels.map(item => item.id)
      //判断是否为空
      if (!this.sels || this.sels.map.length < 1) {
        //提示语
        this.message({managers: "选得数据不能为空，空的你传个得得", type: "error"})
        return;//如果为空直接结束
      }

      this.$confirm('确定要下架？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/product/offsale', ids).then((res) => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message({
              message: '下架成功',
              type: 'success'
            });
            this.getDepartments()
          } else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
      });

    }

  },
  mounted() {
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>